package com.basics.common.utils.weixin;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.*;
import java.security.cert.CertificateException;

/**
 * 调用微信支付统一下单接口所需的HTTP操作工具类
 *
 * @since 2016年8月30日
 * @author wangwei
 *
 */
public class WeixinPayHttpUtil {

	protected static final Logger logger = LoggerFactory.getLogger(WeixinPayHttpUtil.class);

	private final static int CONNECT_TIMEOUT = 10000;

	private static String DEFAULT_ENCODING = "UTF-8";

	public static String postData(String url, String data) {

		return postData(url, data, null);

	}

	public static String postData(String urlStr, String data, String contentType) {

		BufferedReader reader = null;

		try {

			URL url = new URL(urlStr);

			URLConnection conn = url.openConnection();

			conn.setDoOutput(true);
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			conn.setReadTimeout(CONNECT_TIMEOUT);

			if (contentType != null) {

				conn.setRequestProperty("content-type", contentType);

			}

			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);

			if (data == null) {

				data = "";

			}

			writer.write(data);
			writer.flush();
			writer.close();

			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));

			StringBuilder sb = new StringBuilder();

			String line = null;

			while ((line = reader.readLine()) != null) {

				sb.append(line);
				sb.append("\r\n");

			}

			return sb.toString();

		} catch (IOException e) {

			logger.error("Error connecting to " + urlStr + ": " + e.getMessage());

		} finally {

			try {

				if (reader != null) {

					reader.close();

				}

			} catch (IOException e) {

			}

		}

		return null;

	}

	public static String httpReq(String url,String requestXML,String m_id,String certPath){
		KeyStore keyStore;
       	try {
        	keyStore = KeyStore.getInstance("PKCS12");

        	FileInputStream inputStream = new FileInputStream(new File(certPath));
        	try {
        		keyStore.load(inputStream, m_id.toCharArray());
        	} finally {
				inputStream.close();
        	}

        	SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, m_id.toCharArray()).build();
        	SSLConnectionSocketFactory ssl = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" }, null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        	CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssl).build();
        	HttpPost httpPost = new HttpPost(url);
        	StringEntity reqEntity = new StringEntity(requestXML,"UTF-8");
			/**
			 * 设置类型
			 */
			reqEntity.setContentType("application/x-www-form-urlencoded");
	         httpPost.setEntity(reqEntity);
	         CloseableHttpResponse response = httpclient.execute(httpPost);
	         HttpEntity entity = response.getEntity();
	         if (response.getStatusLine().getStatusCode() >= 300) {
	         throw new Exception(
	          "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
	         }

	         if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
		         String responseContent = EntityUtils.toString(entity, "UTF-8");
		         EntityUtils.consume(entity);
		         return responseContent;
	         }
	        } catch (KeyStoreException e) {
	        e.printStackTrace();
	        } catch (IOException e) {
	        e.printStackTrace();
	        } catch (CertificateException e) {
	        e.printStackTrace();
	        } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	        } catch (UnrecoverableKeyException e) {
	        e.printStackTrace();
	        } catch (KeyManagementException e) {
	        e.printStackTrace();
	        } catch (Exception e) {
	        e.printStackTrace();
	        }
       	return null;
	}

}
